import { topicApi } from '/api/topic'
import { userApi } from '/api/user'
import { GlobalData } from '/store/state'
import { checkAuth } from '/store/actions'
import { $event, $logger, $utils } from '/utils'
import { taskApi } from '/api/task'
import { getServer } from '/store/mutations'

interface PageQuery extends WechatMiniprogram.IAnyObject {
  /** 圈子ID */
  topicId: string
  scene?: string
}

Page({
  data: {
    topic: {} as DomoTopic,
    user: {} as DomoUser,
    feeds: [] as DomoFeedWithIndex[],
    ranks: [] as DomoTopicRank[],
    logs: [] as DomoTopicRewardLog[],
    shareImage: '',
    access: {},
    share: false,
    noMore: false,
    mineId: Number,
    currencyName: GlobalData.currencyName,
    topicId: 0 as number,
    /** 积分不足的弹窗 */
    paytoast: false,
    can_pub: false,
    scrollTop: false,
    navigationHeight: GlobalData.navigationHeight,
  },
  async onLoad(query: PageQuery) {
    // wx.hideShareMenu()
    let topicId = query.topicId ? +query.topicId : +query.id
    if (!topicId && query.scene) {
      const scene = $utils.parseQueryString(query.scene)
      topicId = scene.topicId ? +scene.topicId : +scene.id
    }
    this.setData({
      topicId,
    })
  },
  async onShow() {
    await this.getTopic()
    this.getPosition()
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    $event.on('after:operation', this, () => {
      this.setData({
        [`topic.logs_count`]: this.data.topic.logs_count - 1,
      })
    })
    $event.on('after:joinTopic', this, (topic: DomoTopic) => {
      this.canPub()
      this.setData({
        topic,
      })
    })
    $event.on('after:topicEditor', this, async () => {
      await this.getTopic()
      $event.emit('after:joinTopic', this.data.topic)
    })
    $event.on('after:reward', this, () => {
      this.fetchRanks()
      this.getTopic()
    })
    if (this.data.share) {
      const shareSuccess: any = await taskApi.finishShareTopicTask(this.data.topic.id)
      if (shareSuccess.amount) {
        $event.emit('showMessage', {
          message: '分享圈子',
          amount: shareSuccess.amount,
        } as GetRewardMessageReturns)
      }
      this.setData({
        share: false,
      })
    }
    const token = wx.getStorageSync(`${getServer()}/accessToken`).data
    if (token) {
      this.canPub()
      this.getUserId()
    }
    await checkAuth()
  },
  /** 发言检测 */
  async canPub() {
    const { can_pub } = await topicApi.canPublishInTopic(this.data.topicId)
    this.setData({
      can_pub,
    })
  },
  async getTopic() {
    try {
      const topic = await topicApi.getTopicDetail(this.data.topicId)
      this.setData({ topic })
      this.fetchFeeds()
      this.fetchRanks()
      await this.fetchUser()
    } catch (error) {
      $logger.debug('圈子详情加载失败', { error })
    }
  },
  async onPullDownRefresh() {
    await this.getTopic()
    wx.stopPullDownRefresh()
  },
  getPosition() {
    this.setData({
      position: GlobalData.menuRect,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  onShareAppMessage() {
    this.setData({
      share: true,
    })
    const shareInfo: WechatMiniprogram.Page.ICustomShareContent = {
      path: $utils.getSharePath(),
    }
    return shareInfo
  },
  async fetchFeeds() {
    const feeds = await topicApi.getTopicFeeds(this.data.topic.id, { limit: 15 })
    const feeds3 = feeds.slice(0, 4)
    this.setData({
      feeds: !this.data.topic.has_followed && this.data.topic.expense > 0 ? feeds3 : feeds,
      noMore: feeds.length < 15,
    })
  },
  async onReachBottom() {
    if (this.data.noMore || (!this.data.topic.has_followed && this.data.topic.expense > 0)) return
    wx.showLoading({ title: '加载中' })
    const last: number = this.data.feeds[this.data.feeds.length - 1].id
    const res = await topicApi.getTopicFeeds(this.data.topic.id, { index: last, limit: 15 })
    const noMore = res.length < 15
    this.setData({
      feeds: [...this.data.feeds, ...res],
      noMore,
    })
    wx.hideLoading()
  },
  async fetchRanks() {
    let [ranks, logs] = await Promise.all([
      topicApi.getTopicRankUsers(this.data.topic.id, { limit: 6 }),
      topicApi.getTopicRewardLogs(this.data.topic.id),
    ])
    const uids = ranks.map((r) => r.user_id)
    uids.push(...logs.map((r) => r.user_id))
    if (uids.length > 0) {
      const users = await userApi.getUser(uids)
      ranks = ranks.map((r) => {
        r.user = users.find((u) => u.id === r.user_id)
        return r
      })
      logs = logs.map((r) => {
        r.user = users.find((u) => u.id === r.user_id)
        return r
      })
      this.setData({ ranks, logs })
    }
  },
  async fetchUser() {
    const user = await userApi.getUser(this.data.topic.creator_user_id)
    this.setData({ user })
  },
  async onFollowTopic(e: WechatMiniprogram.CustomEvent) {
    await checkAuth()
    const mineId = this.getUserId()
    if (+mineId === +e.currentTarget.dataset.id) return
    if (this.data.topic.has_followed) {
      await topicApi.unfollowTopic(this.data.topic.id)
    } else {
      await topicApi.followTopic(this.data.topic.id)
    }
    this.setData({
      'topic.has_followed': !this.data.topic.has_followed,
    })
  },
  async onReward(e: WechatMiniprogram.CustomEvent) {
    await checkAuth()
    const mineId = this.getUserId()
    if (+mineId === +e.currentTarget.dataset.id) {
      wx.showToast({
        title: '不能打赏自己',
        icon: 'none',
      })
      return
    }
    if (!GlobalData.access.reward) {
      wx.showToast({
        title: '打赏功能已关闭',
        icon: 'none',
      })
      return
    }
    $event.emit('reward', { topicId: this.data.topic.id })
  },
  /** 查看圈子头像 */
  // priview(e: WechatMiniprogram.BaseEvent) {
  //   const topic = e.currentTarget.dataset.topic
  //   wx.previewImage({
  //     current: topic.logo.url,
  //     urls: [topic.logo.url],
  //   })
  // },

  viewRanks() {
    wx.navigateTo({ url: `/pages/topic/ranks/ranks?topicId=${this.data.topic.id}` })
  },
  getUserId() {
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data
    this.setData({
      mineId: user.id,
    })
    return user.id
  },
  /** 成员列表 */
  toMerber() {
    if (this.data.topic.followers_count < 1) return
    wx.navigateTo({
      url: `/pages/topic/member/member?id=${this.data.topic.id}&iscreater=${
        this.data.user.id === +this.data.mineId
      }`,
    })
  },
  /** 加入圈子 */
  join() {
    const topic = this.data.topic
    if (topic.expense > 0) {
      return this.setData({
        paytoast: true,
      })
    }
    topicApi
      .followTopic(topic.id)
      .then(() => {
        this.changeTopic(topic)
      })
      .catch((res) => {
        if (res.data.message === '积分不足') {
          this.setData({
            paytoast: true,
          })
        } else {
          wx.showToast({
            title: '加入失败,稍后重试',
            icon: 'none',
          })
        }
      })
  },
  /** 加入圈子触发 */
  changeTopic(topic: DomoTopic) {
    topic.join_mode === 'need-audit' && topic.expense === 0
      ? // eslint-disable-next-line require-atomic-updates
        (topic.apply_for_status = 'waiting')
      : // eslint-disable-next-line require-atomic-updates
        (topic.has_followed = true)
    this.setData({
      topic,
    })
    $event.emit('after:joinTopic', topic)
  },
  /** 操作 */
  operation() {
    if (!this.data.user.id) return

    const itemList: any[] = []

    const isMine = +this.data.user.id === +this.data.mineId
    const abilities: any = GlobalData.userAbilities
    const canDelte =
      isMine ||
      (abilities &&
        abilities.some((i: any) => {
          return i.name === '[feed] Delete Feed Topic'
        }))

    if (isMine) {
      itemList.push('编辑')
    }
    if (canDelte) {
      itemList.push('删除')
    } else {
      itemList.push('举报')
    }

    if (!isMine && this.data.topic.has_followed) {
      itemList.push('退出圈子')
    }

    wx.showActionSheet({
      itemList: itemList,
      success: (res) => {
        switch (itemList[res.tapIndex]) {
          case '编辑':
            //编辑
            wx.navigateTo({
              url: `/mine/create-topic/create-topic?editor=true`,
            })
            break
          case '退出圈子':
            //退出
            topicApi
              .singOutTopic(this.data.topic.id)
              .then(() => {
                const topic = this.data.topic
                topic.has_followed = false
                topic.followers_count -= 1
                this.setData({
                  topic,
                })
                $event.emit('after:joinTopic', topic)
              })
              .catch(() => {
                wx.showToast({
                  title: '退出失败',
                  icon: 'none',
                })
              })
            break
          case '删除':
            topicApi
              .deleteTopic(this.data.topic.id)
              .then(() => {
                wx.showToast({
                  title: '删除成功',
                })
                $event.emit('after:deleteTopic', this.data.topic)
                setTimeout(() => {
                  wx.navigateBack({ delta: 1 })
                }, 1000)
              })
              .catch(() => {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none',
                })
              })
            break

          case '举报':
            wx.navigateTo({
              url: `/pages/report/report?type=topic&id=${this.data.topic.id}`,
            })
            break
        }
      },
    })
  },
  onPageScroll() {
    this.fixedTitle()
  },
  /** 判断是否滚动到了点评 */
  fixedTitle() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#title').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].top < 1 + this.data.navigationHeight : true,
      })
    })
  },
})
